package com.pearl.jacksoncore.demo.databind.anno;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.DatabindContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase;
import com.fasterxml.jackson.databind.type.TypeFactory;

/**
 * @author TD
 * @version 1.0
 * @date 2024/3/28
 */
public class CustomTypeIdResolver extends TypeIdResolverBase {



    static class ExtResolver extends CustomTypeIdResolver {
        public ExtResolver() {
            super(BaseClass.class, ChildClass1.class);
        }
    }

    protected final Class<?> superType;
    protected final Class<?> subType;


    public CustomTypeIdResolver(Class<?> baseType, Class<?> implType) {
        superType = baseType;
        subType = implType;
    }

    @Override
    public String idFromValue(Object value) {
        // 根据值生成类型 ID 的逻辑
        if (superType.isAssignableFrom(value.getClass())) {
            return "*";
        }
        return "unknown";
    }

    @Override
    public String idFromValueAndType(Object value, Class<?> suggestedType) {
        // 根据值和类型生成类型 ID 的逻辑
        return idFromValue(value);
    }

    @Override
    public JavaType typeFromId(DatabindContext context, String id) {
        if ("*".equals(id)) {
            return TypeFactory.defaultInstance().constructType(subType);
        }
        return null;
    }

    @Override
    public JsonTypeInfo.Id getMechanism() {
        return JsonTypeInfo.Id.CUSTOM;
    }


}